package main

import (
	"flag"
	"fmt"
	"log"
	"net"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"
)

/*
var ip = flag.String("ip", "127.0.0.1", "云端服务器ip地址")
var port = flag.Int("port", 39999, "云端服务器端口")
*/
/*
var id = flag.String("id", "abcd@edge", "边缘id")
var targetIP = flag.String("targetIP", "14.215.177.39", "目标ip")
var targetPort = flag.Int("targetPort", 80, "目标端口")
var netType = flag.String("netType", "tcp", "连接类型")
*/
var portSpecified = flag.String("p", "0", "指定端口")

func main() {

	flag.Parse()
	//go client.BeginClientTunnel(*ip, *port)
	fmt.Println("*************", *portSpecified)
	file, _ := exec.LookPath(os.Args[0])
	path, err := filepath.Abs(file)
	//dir = "d:/work/node/TS/bin"
	//dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	dir := filepath.Dir(path)
	if !strings.Contains(dir, "bin") {
		dir = dir + "/bin"
	}

	if err != nil {
		log.Fatal(err)
	}

	dir = dir + "/dist"

	http.Handle("/", http.FileServer(http.Dir(dir)))
	http.HandleFunc("/api/list", getEdgeList)
	http.HandleFunc("/api/edge/", wakeupList)
	http.HandleFunc("/api/begin/", begin)
	http.HandleFunc("/api/mscan", scanEdges)
	http.HandleFunc("/api/interfaces/", getInterfaces)
	//listener, _ := net.Listen("tcp", ":0")

	listener, _ := net.Listen("tcp", ":"+*portSpecified)
	port := listener.Addr().(*net.TCPAddr).Port
	fmt.Println("-----------", dir, port)
	if *portSpecified == "0" {
		go func(port int) {
			fmt.Println("------------run ui-----------")
			cmd := exec.Command("cmd", "/c", "start", "http://127.0.0.1:"+strconv.Itoa(port))
			cmd.Start()
		}(port)
	}

	err = http.Serve(listener, nil)
	//err = http.ListenAndServe("0.0.0.0:29000", nil)
	fmt.Println("err-------------", err)

}
